﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraTabbedMdi;
using MDIDemo.Modules;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;


namespace MDIDemo
{
    /// <summary>
    /// Summary description for frmMain.
    /// </summary>
    /// 

    public partial class frmMain : DevExpress.XtraEditors.XtraForm
    {
        string sErr = "";
        public static string __userID = "";
        private static bool status = false;
        public static DateTime __ngayMoSo
        {
            get
            {
                string sErr = "";
                BUS.REFERGDControl ctr = new BUS.REFERGDControl();
                DataTable dt = ctr.GetAll(ref sErr);
                if (sErr == "")
                {
                    if (dt.Rows.Count > 0)
                    {
                        DTO.REFERGDInfo inf = new DTO.REFERGDInfo(dt.Rows[0]);
                        //string str = inf.KHOASO ? "Khóa sổ" : "Mở sổ";

                        return inf.NGAYGD;
                        //return inf.KHOASO;
                    }
                }
                return DateTime.Today;
            }
        }
        public static string GetWebPageResult(string url)
        {
            WebRequest wrGETURL = WebRequest.Create(url);
            string content = "";
            try
            {
                using (Stream objStream = wrGETURL.GetResponse().GetResponseStream())
                {
                    using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8))
                    {
                        using (WebResponse wr = wrGETURL.GetResponse())
                        {
                            using (Stream receiveStream = wr.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8))
                                {
                                    content = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            return content;

        }
        public static bool __khoaSo
        {
            get
            {
                string sErr = "";
                BUS.REFERGDControl ctr = new BUS.REFERGDControl();
                DataTable dt = ctr.GetAll(ref sErr);
                if (sErr == "")
                {
                    if (dt.Rows.Count > 0)
                    {
                        DTO.REFERGDInfo inf = new DTO.REFERGDInfo(dt.Rows[0]);
                        //string str = inf.KHOASO ? "Khóa sổ" : "Mở sổ";
                        status = inf.KHOASO;
                        //frmMain.__ngayMoSo = inf.NGAYGD;
                        return inf.KHOASO;
                    }
                }
                return true;
            }

        }
        public static string AppPath
        {
            get { return String.Format("{0}\\{1}", Application.StartupPath, Properties.Settings.Default.AppPath); }
        }
        public static string ReportPath
        {
            get { return String.Format("{0}\\{1}", AppPath, Properties.Settings.Default.ReportPath); }
        }
        public static string ReportOut
        {
            get { return String.Format("{0}\\{1}", AppPath, Properties.Settings.Default.ReportOut); }
        }
        public static string ConfigPath
        {
            get { return String.Format("{0}\\{1}", AppPath, Properties.Settings.Default.ConfigPath); }
        }
        public frmMain()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //colorEdit.EditValue = Color.Empty;
            //ImageComboBoxItem[] piis = new ImageComboBoxItem[] {new ImageComboBoxItem("Clip", PictureSizeMode.Clip), new ImageComboBoxItem("Stretch", PictureSizeMode.Stretch), 
            //    new ImageComboBoxItem("Zoom", PictureSizeMode.Zoom), new ImageComboBoxItem("Squeeze", PictureSizeMode.Squeeze)};
            //foreach (ImageComboBoxItem pii in piis)
            //    ((DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox)sizeMode.Edit).Items.Add(pii);
            //InitBars();
            //barManager1.GetController().Changed += new EventHandler(ChangedController);
            //ips_Init();
            InitSkins();
            InitTabbedMDI();
            //InitPictures();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            DevExpress.XtraEditors.Controls.Localizer.Active = new MyEditorLocalizer();
            DevExpress.XtraGrid.Localization.GridLocalizer.Active = new MyGridLocalizer();

        }
        public XtraForm ShowReport(DataSet ds, string reportCode, string reportName)
        {
            XtraForm frm = new PrintPreview();
            ((PrintPreview)frm).DataSource = ds;
            ((PrintPreview)frm).ReportCode = reportCode;
            frm.Text = reportName;
            LoadForm(frm, false);
            return frm;
        }
        public XtraForm ShowReport(DataSet ds, string reportCode, string reportName, Dictionary<string, object> val)
        {
            XtraForm frm = new PrintPreview();
            ((PrintPreview)frm).DataSource = ds;
            ((PrintPreview)frm).ReportCode = reportCode;
            ((PrintPreview)frm).ValueList = val;
            frm.Text = reportName;
            LoadForm(frm, false);
            return frm;
        }
       

        const string imageFormName = "image";
        const string textFormName = "text";
        const string textRTFFormName = "rtf";
        Cursor currentCursor;
        string skinMask = "Skin: ";
        int oldActive = -2;
        int lockUpdate = 0;

        #region Skins

        void InitSkins()
        {
            barManager1.ForceInitialize();
            foreach (DevExpress.Skins.SkinContainer cnt in DevExpress.Skins.SkinManager.Default.Skins)
            {
                if (!cnt.SkinName.Contains("DevExpress"))
                {
                    BarButtonItem item = new BarButtonItem(barManager1, cnt.SkinName);
                    iGiaoDien.AddItem(item);
                    item.Tag = cnt.SkinName;
                    try
                    {
                        string file = cnt.SkinName.Replace(" ", "_") + "___16x16";
                        item.Glyph = (Image)Properties.Resources.ResourceManager.GetObject(file);
                    }
                    catch { }
                    if (DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName == cnt.SkinName)
                    {
                        item.Enabled = false;
                    }
                    item.ItemClick += new ItemClickEventHandler(OnSkinClick);
                }
            }
        }
        void OnSkinClick(object sender, ItemClickEventArgs e)
        {
            foreach (BarItem it in iGiaoDien.Manager.Items)
                it.Enabled = true;
            string skinName = e.Item.Tag.ToString();
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(skinName);
            barManager1.GetController().PaintStyleName = "Skin";
            e.Item.Enabled = false;
            Properties.Settings.Default.SkinName = skinName;
            Properties.Settings.Default.Save();
        }
        #endregion
        /*
        private void InitBars()
        {
            iDocName.Caption = (ActiveMDIForm != null) ? ActiveMDIForm.Tag.ToString() : " ";
            iFont.Enabled = IsActiveTextRTFForm;
            InitEdit();
            InitPicture();
            if (oldActive == NumActive) return;
            iDonViTinh.Enabled = iQLBH.Enabled = ActiveMDIForm != null;
            iRotateBy90.Enabled = iHorizontalFlip.Enabled = iVerticalFlip.Enabled =
                iPictureAlignment.Enabled = sizeMode.Enabled = IsActiveImageForm;
            iSelectAll.Enabled = colorEdit.Enabled = IsActiveTextForm;

            for (int i = iQLBH.ItemLinks.Count - 1; i >= 0; i--)
                iQLBH.RemoveLink(iQLBH.ItemLinks[i]);

            if (IsActiveImageForm)
            {
                iPicture.ImageIndex = 13;
                iQLBH.AddItem(iHorizontalFlip);
                iQLBH.AddItem(iVerticalFlip);
                iQLBH.AddItem(iRotateBy90);
                iQLBH.Caption = "Image &Edit";
            }
            if (IsActiveTextForm)
            {
                iPicture.ImageIndex = 14;
                iQLBH.AddItem(iCut);
                iQLBH.AddItem(iCopy);
                iQLBH.AddItem(iPaste);
                iQLBH.AddItem(iSelectAll).BeginGroup = true;
                iQLBH.Caption = "Text &Edit";
            }

            if (ActiveMDIForm == null)
            {
                iPicture.ImageIndex = -1;
                iQLBH.Caption = "&Edit";
            }

            oldActive = NumActive;
        }


        private void InitPicture()
        {
            lockUpdate++;
            if (ActivePictureEdit != null)
                sizeMode.EditValue = ActivePictureEdit.Properties.SizeMode;
            else sizeMode.EditValue = PictureSizeMode.Squeeze;
            lockUpdate--;
        }
        private void InitEdit()
        {
            RichTextBox rtb = ActiveRichTextBox;
            if (rtb != null)
            {
                iPaste.Enabled = rtb.CanPaste(DataFormats.GetFormat(0));
                iCut.Enabled = iCopy.Enabled = rtb.SelectedText != "";
                lockUpdate++;
                colorEdit.EditValue = rtb.SelectionColor;
                lockUpdate--;
            }
            else
            {
                iCut.Enabled = iCopy.Enabled = iPaste.Enabled = false;
            }
        }
        */
        private void RefreshForm(bool b)
        {
            if (b)
            {
                currentCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;
                Refresh();
            }
            else
                Cursor.Current = currentCursor;
        }

        private int NumActive
        {
            get
            {
                if (IsActiveTextForm) return 1;
                if (IsActiveImageForm) return 0;
                return -1;
            }
        }
        private Form ActiveMDIForm
        {
            get { return this.ActiveMdiChild; }
        }

        private bool GetIsImageForm(Form form)
        {
            return form != null && form.AccessibleName == imageFormName;
        }
        private bool IsActiveImageForm
        {
            get { return GetIsImageForm(ActiveMDIForm); }
        }

        private bool IsActiveTextForm
        {
            get { return (ActiveMDIForm != null && ActiveMDIForm.AccessibleName == textFormName); }
        }

        private bool IsActiveTextRTFForm
        {
            get { return (IsActiveTextForm && ActiveMDIForm.AccessibleDescription == textRTFFormName); }
        }

        private PictureEdit GetPictureEdit(Form form)
        {
            if (GetIsImageForm(form))
                return (PictureEdit)form.Controls[0];
            else
                return null;
        }
        private DevExpress.XtraEditors.PictureEdit ActivePictureEdit
        {
            get
            {
                return GetPictureEdit(ActiveMDIForm);
            }
        }

      

      

        void UpdateMdiPictureFormPreview(XtraMdiTabPage page, Image img)
        {
            if (page == null)
                return;
            Image preview = null;
            const int previewHeight = 32;
            const int previewWidthMax = 64;
            //int previewHeight = this.imageList3.ImageSize.Height;
            if (img != null && img.Height > 0 && previewHeight > 0)
            {
                int previewWidth = previewHeight * img.Width / img.Height;
                if (previewWidth > 0)
                {
                    if (previewWidth > previewWidthMax)
                        previewWidth = previewWidthMax;
                    preview = new Bitmap(img, previewWidth, previewHeight);
                }
            }
            page.Image = preview;
        }

       
      

      

        private void frmMain_MdiChildActivate(object sender, System.EventArgs e)
        {
            //InitBars();
        }

        private void iClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActiveMDIForm != null)
                ActiveMDIForm.Close();
        }

        private void FlipRotate(RotateFlipType type)
        {
            if (IsActiveImageForm)
            {
                currentCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;

                Image image = ActivePictureEdit.Image.Clone() as Image;
                image.RotateFlip(type);
                ActivePictureEdit.Image = image;

                UpdateMdiPictureFormPreview(this.xtraTabbedMdiManager1.SelectedPage, image);

                Cursor.Current = currentCursor;
            }
        }

        private void iHorizontalFlip_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FlipRotate(RotateFlipType.RotateNoneFlipX);
        }

        private void iVerticalFlip_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FlipRotate(RotateFlipType.RotateNoneFlipY);
        }

        private void iRotateBy90_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FlipRotate(RotateFlipType.Rotate90FlipNone);
        }

        private void iExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }

        void PictureAlignmentChanged(object sender, EventArgs e)
        {
            //if (ActivePictureEdit != null)
            //    ActivePictureEdit.Properties.PictureAlignment = alignmentControl1.Alignment;
        }

        void popupControlContainer1_Popup(object sender, System.EventArgs e)
        {
            //if (ActivePictureEdit == null) return;
            //alignmentControl1.Alignment = ActivePictureEdit.Properties.PictureAlignment;
        }

        private void iCascade_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }

        private void iDieuChinhKho_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XtraForm frm = new DieuChinhKho();
            LoadForm(frm, false);
        }

        //private void iTileVertical_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    this.LayoutMdi(MdiLayout.TileVertical);
        //}

        private void iWeb_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "http://www.devexpress.com";
            process.StartInfo.Verb = "Open";
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            process.Start();
        }

      

       


        bool IsTabbedMdi { get { return iNhapKho.Down; } }

        void InitTabbedMDI()
        {
            xtraTabbedMdiManager1.MdiParent = this; //IsTabbedMdi ? this : null;
            //iCascade.Visibility = iDieuChinhKho.Visibility = iTileVertical.Visibility = IsTabbedMdi ? BarItemVisibility.Never : BarItemVisibility.Always;
        }

        private void iNhapKho_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XtraForm frm = new NhapKho();
            LoadForm(frm, false);
        }

        private void xtraTabbedMdiManager1_PageAdded(object sender, DevExpress.XtraTabbedMdi.MdiTabPageEventArgs e)
        {
            PictureEdit pictureEdit = GetPictureEdit(e.Page.MdiChild);
            Image image = (pictureEdit == null) ? null : pictureEdit.Image;
            UpdateMdiPictureFormPreview(e.Page, image);
        }

        private void iPass_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new DoiMatKhau();
            LoadForm(frm, true);
        }

        private void LoadForm(XtraForm frm, bool isForm)
        {
            bool flag = false;
            foreach (DevExpress.XtraEditors.XtraForm x in this.MdiChildren)
            {
                if (x.Text == frm.Text)
                {
                    flag = true;
                    x.Focus();
                }
            }
            if (flag == false)
            {
                if (isForm)
                    frm.ShowDialog();
                else { CreateMDIForm(frm); }

            }
        }

        private void CreateMDIForm(XtraForm frm)
        {
            frm.MdiParent = this;
            frm.Show();
        }

        private void iUser_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new NguoiDung();
            LoadForm(frm, false);
        }

        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new PhanQuyen();
            LoadForm(frm, false);
        }

        private void iDonViTinh_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new DonViTinh();
            LoadForm(frm, false);
        }

        private void iItems_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new HangHoa();
            LoadForm(frm, false);
        }

        private void iPrice_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new GiaBan();
            LoadForm(frm, false);
        }

        private void iCustomer_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new KhachHang();
            LoadForm(frm, false);
        }

        private void iSystem_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new HeThong();
            ((HeThong)frm).Main = this;
            LoadForm(frm, true);
        }

        private void iHDHangHoa_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new HoaDonItem();
            LoadForm(frm, false);
        }

        private void iNXHoaDon_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new NXHoaDon();
            LoadForm(frm, false);
        }

        private void iThuChiHD_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new ThuChiHoaDon();
            LoadForm(frm, false);
        }

        private void iChuyenKhoanHD_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new ChuyenKhoanHD();
            LoadForm(frm, false);
        }



        private void iSale_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (frmMain.__ngayMoSo < DateTime.Today)
                if (XtraMessageBox.Show("Bạn đang mở số trước ngày hiện hành, bạn có chắc muốn tiếp tục xuất hàng?", "Thông báo", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
            XtraForm frm = new XuatHang();
            LoadForm(frm, false);
        }

        private void iPayment_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new ThuChiTM();
            LoadForm(frm, false);
        }


        private void iPaySale_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new ThuTrongNgay();
            LoadForm(frm, false);
        }

        private void iLiabilities_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new CongNo();
            LoadForm(frm, false);
        }
        DTO.PODInfo currentUser = null;
        public static string StringToBase64(string str)
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
            string b64 = Convert.ToBase64String(b);
            return b64;
        }


        public static string Base64ToString(string b64)
        {
            byte[] b = Convert.FromBase64String(b64);
            return (System.Text.Encoding.UTF8.GetString(b));
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            BUS.CommonControl ctrCOM = new BUS.CommonControl();
            DataTable dt = ctrCOM.executeSelectQuery("Select * from HETHONG");
            string id = "";
            if (dt.Rows.Count > 0)
            {
                id = iDocName.Caption = dt.Rows[0]["TenDV"].ToString() + " - " + dt.Rows[0]["DiaChi"].ToString();
            }

            object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
            if (attributes.Length > 0)
            {
                string url = ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion;

                url += "?id=" + StringToBase64(id);
                string resutle = GetWebPageResult(url);
                if (resutle == "False")
                {
                    XtraMessageBox.Show("This version is not license, please contact to nnamthach@gmail.com get more information");
                    Close(); return;
                }
                else if (Regex.IsMatch(resutle, "^[0-9]+$"))
                {
                    XtraMessageBox.Show("This system is trial version, you can use this " + resutle + " times, please contact to nnamthach@gmail.com get more information");
                }
            }

            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            sVersion.Caption = "Version: " + version;


            sDate.Caption = "Ngày giao dịch : " + frmMain.__ngayMoSo.ToString("dd/MM/yyyy");
            BUS.PODControl ctr = new BUS.PODControl();
            currentUser = ctr.Get(frmMain.__userID, ref sErr);
            sUser.Caption = String.Format("Người sử dụng : {0} - {1}", currentUser.USER_ID, currentUser.USER_NAME);
            sLogtime.Caption = "Thời gian đăng nhập : " + DateTime.Now.ToString("dd/MM/yyyy hh:mm tt");
            if (__khoaSo)
            {
                sSystem.Appearance.ForeColor = Color.Red;

                sSystem.Caption = "Tình trạng : Khóa sổ";
            }
            else
            {
                sSystem.Appearance.ForeColor = Color.Blue;
                sSystem.Caption = "Tình trạng : Chưa khóa sổ";
            }

            SetPermission();
        }
        #region Permission
        int idMoSo = 1;
        int idKhoaSo = 2;
        int idNguoiDung = 3;
        int idPhanQuyen = 7;
        int idDVT = 11;
        int idHangHoa = 15;
        int idGiaBan = 19;
        int idKhachHang = 22;
        int idDKDLHeThong = 26;
        int idHeThong = 78;
        int idQLBH = 79;
        int idKTTH = 80;
        int idQLK = 81;
        int idNhapKho = 82;
        int idDieuChinhTon = 86;
        int idXuatBanHang = 28;
        int idThuChiTM = 32;
        int idThuChiTrongNgay = 36;
        int idQuanLyCN = 40;
        int idHangHoaHD = 44;
        int idNXHoaDon = 48;
        int idThuChiHD = 52;
        int idChuyenKhoanHD = 56;
        int idBaoCaoBH = 63;
        int idBaoCaoNKGiaoDich = 64;
        int idBaoCaoBanGiaoCN = 65;
        int idBaoCaoCongNoPS = 66;
        int idBaoCaoCongNoNgay = 67;
        int idBaoCaoDoanhSoBH = 68;
        int idBaoCaoDoanhSoLoaiHang = 69;
        int idBaoCaoDoanhThuLoiNhuan = 70;
        int idBaoCaoChiTietTonKho = 71;
        int idBaoCaoKT = 72;
        int idBaoCaoGTGT = 73;
        int idBaoCaoDoanhSoTheoKhachHang = 74;
        int idBaoCaoDanhMucTonHang = 75;
        int idBaoCaoNXHang = 76;
        int idBaoCaoDoanhSoGTGT = 77;
        int idBaoCaoThuChiTMTheoNgay = 92;
        int idBaoCaoChiTietNhapKho = 93;

        private void SetPermission()
        {
            if (currentPermis == null)
            {
                BUS.POPControl ctr = new BUS.POPControl();
                currentPermis = ctr.Get(currentUser.ROLE_ID, "", ref sErr);
            }
            if (IsPermis(idHeThong, currentPermis.PERMISSION))
                iHeThong.Visibility = BarItemVisibility.Always;
            else iHeThong.Visibility = BarItemVisibility.Never;

            if (IsPermis(idQLBH, currentPermis.PERMISSION))
                iQLBH.Visibility = BarItemVisibility.Always;
            else iQLBH.Visibility = BarItemVisibility.Never;

            if (IsPermis(idQLK, currentPermis.PERMISSION))
                iQuanLyKho.Visibility = BarItemVisibility.Always;
            else iQuanLyKho.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoThuChiTMTheoNgay, currentPermis.PERMISSION))
                iBaoCaoThuChiTMTheoNgay.Visibility = BarItemVisibility.Always;
            else iBaoCaoThuChiTMTheoNgay.Visibility = BarItemVisibility.Never;

            if (IsPermis(idKTTH, currentPermis.PERMISSION))
                iKTTH.Visibility = BarItemVisibility.Always;
            else iKTTH.Visibility = BarItemVisibility.Never;

            if (IsPermis(idXuatBanHang, currentPermis.PERMISSION))
            {
                tiBanHang.Visibility = iXuatBan.Visibility = BarItemVisibility.Always;
            }
            else { tiBanHang.Visibility = iXuatBan.Visibility = BarItemVisibility.Never; }

            if (IsPermis(idQuanLyCN, currentPermis.PERMISSION))
            {
                tiCongNo.Visibility = iCongNo.Visibility = BarItemVisibility.Always;
            }
            else { tiCongNo.Visibility = iCongNo.Visibility = BarItemVisibility.Never; }

            if (IsPermis(idThuChiTrongNgay, currentPermis.PERMISSION))
            {
                tiThuTrongNgay.Visibility = iThuChiTrongNgay.Visibility = BarItemVisibility.Always;
            }
            else { tiThuTrongNgay.Visibility = iThuChiTrongNgay.Visibility = BarItemVisibility.Never; }

            if (IsPermis(idBaoCaoBH, currentPermis.PERMISSION))
                iBaocaoBH.Visibility = BarItemVisibility.Always;
            else iBaocaoBH.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoNKGiaoDich, currentPermis.PERMISSION))
                iBaoCaoNKGiaoDich.Visibility = BarItemVisibility.Always;
            else iBaoCaoNKGiaoDich.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoBanGiaoCN, currentPermis.PERMISSION))
                iBaoCaoBanGiaoCN.Visibility = BarItemVisibility.Always;
            else iBaoCaoBanGiaoCN.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoCongNoPS, currentPermis.PERMISSION))
                iBaoCaoCNPS.Visibility = BarItemVisibility.Always;
            else iBaoCaoCNPS.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoCongNoNgay, currentPermis.PERMISSION))
                iBaoCaoCNPS_PT.Visibility = BarItemVisibility.Always;
            else iBaoCaoCNPS_PT.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDoanhSoBH, currentPermis.PERMISSION))
                iBaoCaoDoanhSo.Visibility = BarItemVisibility.Always;
            else iBaoCaoDoanhSo.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDoanhSoLoaiHang, currentPermis.PERMISSION))
                iBaoCaoPhanTichDoanhSo.Visibility = BarItemVisibility.Always;
            else iBaoCaoPhanTichDoanhSo.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDoanhThuLoiNhuan, currentPermis.PERMISSION))
                iBaoCaoDoanhThuLoiNhuan.Visibility = BarItemVisibility.Always;
            else iBaoCaoDoanhThuLoiNhuan.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDoanhThuLoiNhuan, currentPermis.PERMISSION))
                iBaoCaoDoanhThuLoiNhuan.Visibility = BarItemVisibility.Always;
            else iBaoCaoDoanhThuLoiNhuan.Visibility = BarItemVisibility.Never;

            if (IsPermis(idNhapKho, currentPermis.PERMISSION))
            {
                tiNhapHang.Visibility = iNhapKho.Visibility = BarItemVisibility.Always;
            }
            else { tiNhapHang.Visibility = iNhapKho.Visibility = BarItemVisibility.Never; }

            if (IsPermis(idDieuChinhTon, currentPermis.PERMISSION))
                iDieuChinhKho.Visibility = BarItemVisibility.Always;
            else iDieuChinhKho.Visibility = BarItemVisibility.Never;

            if (IsPermis(idHangHoaHD, currentPermis.PERMISSION))
                iHangHoaHD.Visibility = BarItemVisibility.Always;
            else iHangHoaHD.Visibility = BarItemVisibility.Never;

            if (IsPermis(idNXHoaDon, currentPermis.PERMISSION))
                iNXHoaDon.Visibility = BarItemVisibility.Always;
            else iNXHoaDon.Visibility = BarItemVisibility.Never;

            if (IsPermis(idThuChiHD, currentPermis.PERMISSION))
                iThuChiHD.Visibility = BarItemVisibility.Always;
            else iThuChiHD.Visibility = BarItemVisibility.Never;

            if (IsPermis(idChuyenKhoanHD, currentPermis.PERMISSION))
                iChuyenKhoanHD.Visibility = BarItemVisibility.Always;
            else iChuyenKhoanHD.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoKT, currentPermis.PERMISSION))
                iBaoCaoKT.Visibility = BarItemVisibility.Always;
            else iBaoCaoKT.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoGTGT, currentPermis.PERMISSION))
                iBaoCaoGTGT.Visibility = BarItemVisibility.Always;
            else iBaoCaoGTGT.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDoanhSoTheoKhachHang, currentPermis.PERMISSION))
                iBaoCaoDoanhSoTheoKH.Visibility = BarItemVisibility.Always;
            else iBaoCaoDoanhSoTheoKH.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDanhMucTonHang, currentPermis.PERMISSION))
                iBaoCaoTonHang.Visibility = BarItemVisibility.Always;
            else iBaoCaoTonHang.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoNXHang, currentPermis.PERMISSION))
                iBaoCaoNXHang.Visibility = BarItemVisibility.Always;
            else iBaoCaoNXHang.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoDoanhSoGTGT, currentPermis.PERMISSION))
                iBaoCaoThongKeGTGT.Visibility = BarItemVisibility.Always;
            else iBaoCaoThongKeGTGT.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoChiTietTonKho, currentPermis.PERMISSION))
                iBaoCaoChiTietTK.Visibility = BarItemVisibility.Always;
            else iBaoCaoChiTietTK.Visibility = BarItemVisibility.Never;

            if (IsPermis(idBaoCaoChiTietNhapKho, currentPermis.PERMISSION))
                iBaoCaoChiTietNK.Visibility = BarItemVisibility.Always;
            else iBaoCaoChiTietNK.Visibility = BarItemVisibility.Never;

            if (IsPermis(idThuChiTM, currentPermis.PERMISSION))
                iThuChiTM.Visibility = BarItemVisibility.Always;
            else iThuChiTM.Visibility = BarItemVisibility.Never;

            if (IsPermis(idThuChiTrongNgay, currentPermis.PERMISSION))
            {
                tiThuTrongNgay.Visibility = iThuChiTrongNgay.Visibility = BarItemVisibility.Always;
            }
            else { tiThuTrongNgay.Visibility = iThuChiTrongNgay.Visibility = BarItemVisibility.Never; }

            if (IsPermis(idMoSo, currentPermis.PERMISSION))
                tiMoSo.Visibility = BarItemVisibility.Always;
            else tiMoSo.Visibility = BarItemVisibility.Never;

            if (IsPermis(idKhoaSo, currentPermis.PERMISSION))
                tiKhoaSo.Visibility = BarItemVisibility.Always;
            else tiKhoaSo.Visibility = BarItemVisibility.Never;

            if (IsPermis(idNguoiDung, currentPermis.PERMISSION))
                iNguoiDung.Visibility = BarItemVisibility.Always;
            else iNguoiDung.Visibility = BarItemVisibility.Never;

            if (IsPermis(idPhanQuyen, currentPermis.PERMISSION))
                iPhanQuyen.Visibility = BarItemVisibility.Always;
            else iPhanQuyen.Visibility = BarItemVisibility.Never;

            if (IsPermis(idDVT, currentPermis.PERMISSION))
                iDonViTinh.Visibility = BarItemVisibility.Always;
            else iDonViTinh.Visibility = BarItemVisibility.Never;

            if (IsPermis(idHangHoa, currentPermis.PERMISSION))
                iHangHoa.Visibility = BarItemVisibility.Always;
            else iHangHoa.Visibility = BarItemVisibility.Never;

            if (IsPermis(idGiaBan, currentPermis.PERMISSION))
                iGiaBan.Visibility = BarItemVisibility.Always;
            else iGiaBan.Visibility = BarItemVisibility.Never;

            if (IsPermis(idKhachHang, currentPermis.PERMISSION))
            {
                tiKhachHang.Visibility = iKhachHang.Visibility = BarItemVisibility.Always;
            }
            else { tiKhachHang.Visibility = iKhachHang.Visibility = BarItemVisibility.Never; }

            if (IsPermis(idDKDLHeThong, currentPermis.PERMISSION))
                iDLHeThong.Visibility = BarItemVisibility.Always;
            else iDLHeThong.Visibility = BarItemVisibility.Never;
        }

        DTO.POPInfo currentPermis = null;

        public DTO.POPInfo CurrentPermis
        {
            get { return currentPermis; }
            set { currentPermis = value; }
        }


        public static bool IsPermis(int id, string permission)
        {
            if (id >= permission.Length || permission[id] == 'Y')
                return true;
            return false;
        }
        #endregion

        private void tiThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void tiDoiMatKhau_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraForm frm = new DoiMatKhau();
            LoadForm(frm, true);
        }

        private void tiKhachHang_ItemClick(object sender, ItemClickEventArgs e)
        {
            iCustomer_ItemClick(null, null);
        }

        private void tiBanHang_ItemClick(object sender, ItemClickEventArgs e)
        {
            iSale_ItemClick(null, null);
        }

        private void tiThuTrongNgay_ItemClick(object sender, ItemClickEventArgs e)
        {
            iPaySale_ItemClick(null, null);
        }

        private void tiCongNo_ItemClick(object sender, ItemClickEventArgs e)
        {
            iLiabilities_ItemClick(null, null);
        }

        private void tiNhapHang_ItemClick(object sender, ItemClickEventArgs e)
        {
            iNhapKho_ItemClick(null, null);
        }

        private void tiKhoaSo_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (frmMain.__khoaSo == false)
            {
                if (XtraMessageBox.Show("Bạn có chắc muốn khóa sổ?", "Thông báo", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    BUS.REFERGDControl ctr = new BUS.REFERGDControl();
                    DataTable dt = ctr.GetAll(ref sErr);
                    DTO.REFERGDInfo inf = new DTO.REFERGDInfo();
                    if (dt.Rows.Count > 0)
                    {
                        inf = new DTO.REFERGDInfo(dt.Rows[0]);
                    }
                    else
                        inf.NGAYGD = DateTime.Today;
                    inf.KHOASO = true;
                    inf.SOCT = "";
                    ctr.InsertUpdate(inf);
                    //frmMain.__khoaSo = true;
                    frmMain_Load(null, null);
                    ClearMdi();
                }
            }
            else XtraMessageBox.Show("Sổ đang khóa", "Thông báo");
        }



        private void tiMoSo_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (frmMain.__khoaSo == true)
            {
                Windows.frmDate frm = new Windows.frmDate();
                frm.SelectedDate = frmMain.__ngayMoSo;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (frm.SelectedDate < DateTime.Today)
                        if (XtraMessageBox.Show("Bạn đang mở số trước ngày hiện hành, bạn có chắc muốn mở sổ ngày này?", "Thông báo", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)
                            return;
                    BUS.REFERGDControl ctr = new BUS.REFERGDControl();
                    DataTable dt = ctr.GetAll(ref sErr);
                    DTO.REFERGDInfo inf = new DTO.REFERGDInfo();
                    if (dt.Rows.Count > 0)
                    {
                        inf = new DTO.REFERGDInfo(dt.Rows[0]);
                    }
                    else
                        inf.NGAYGD = DateTime.Today;
                    inf.NGAYGD = frm.SelectedDate;
                    inf.KHOASO = false;
                    inf.SOCT = "";
                    ctr.Delete();
                    ctr.InsertUpdate(inf);
                    //frmMain.__khoaSo = false;
                    //frmMain.__ngayMoSo = inf.NGAYGD;
                    frmMain_Load(null, null);
                    ClearMdi();
                }
            }
            else XtraMessageBox.Show("Sổ đang mở", "Thông báo");
        }

        private void tiThoat_ItemClick(object sender, ItemClickEventArgs e)
        {
            Close();
        }

        private void iBaoCaoGTGT_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBangKeGTGT frm = new Windows.Report.frmBangKeGTGT();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void iXuatHTKK_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void iBaoCaoTonHang_ItemClick(object sender, ItemClickEventArgs e)
        {
            DataSet _ds = new DataSet();
            string query = @"SELECT     MAHANG, TENHANG, DVTINH, SOLUONG, SOTIEN, GIAVON, GIABAN, CREATEBY, MODIFIEDBY, CREATEDATE, MODIFIEDDATE
FROM         TONHANG
WHERE SOLUONG>=1";
            BUS.CommonControl ctr = new BUS.CommonControl();
            _ds = ctr.executeSelectQueries(query);
            Dictionary<string, object> val = new Dictionary<string, object>();
            val.Add("NgayMoSo", frmMain.__ngayMoSo);
            ShowReport(_ds, "TONHANG", "Báo cáo tồn hàng", val);
        }

        private void iBaoCaoNXHang_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoNXTonHang frm = new Windows.Report.frmBaoCaoNXTonHang();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void iBaoCaoThongKeGTGT_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoDoanhSoGTGT frm = new Windows.Report.frmBaoCaoDoanhSoGTGT();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void iBaoCaoChiTietTK_ItemClick(object sender, ItemClickEventArgs e)
        {
            DataSet _ds = new DataSet();
            string query = @"SELECT   ROW_NUMBER ( )     OVER ( ORDER BY TONKHO.MAHANG ) as STT,  TONKHO.NHOMHANG, TONKHO.MAHANG, TONKHO.SOLUONG,TONKHO.GIAVON, TONKHO.SOTIEN, NHOMHANG.TENNHOM, LOAIHANG.TENHANG, LOAIHANG.DVTINH, 
                      LOAIHANG.QUYCACH
FROM         TONKHO INNER JOIN
                      LOAIHANG ON TONKHO.MAHANG = LOAIHANG.MAHANG INNER JOIN
                      NHOMHANG ON TONKHO.NHOMHANG = NHOMHANG.NHOMHANG
            WHERE TONKHO.SOLUONG>=1";
            BUS.CommonControl ctr = new BUS.CommonControl();
            _ds = ctr.executeSelectQueries(query);
            Dictionary<string, object> val = new Dictionary<string, object>();
            val.Add("Date", frmMain.__ngayMoSo);
            ShowReport(_ds, "TONKHO", "Báo cáo chi tiết nhập kho", val);
        }

        private void iBaoCaoNKGiaoDich_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoNKGiaoDich frm = new Windows.Report.frmBaoCaoNKGiaoDich();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, "BKGDCT", "Báo cáo giao dịch chi tiết", frm.ValueList);
            }
        }

        private void iBaoCaoBanGiaoCN_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoBGCNPhatSinh frm = new Windows.Report.frmBaoCaoBGCNPhatSinh();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, "BGCNPS", "Phiếu bàn giao công nợ phát sinh");
            }
        }

        private void iBaoCaoCNPS_PT_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoCongNo frm = new Windows.Report.frmBaoCaoCongNo();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.Type == "BH")
                    ShowReport(frm.DataSource, "BCCNPT", "Báo cáo công nợ", frm.ValueList);
                else
                    ShowReport(frm.DataSource, "BCCNPTR", "Báo cáo công nợ", frm.ValueList);
            }
        }

        private void iBaoCaoDoanhSo_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoDoanhSoTheoThoiGian frm = new Windows.Report.frmBaoCaoDoanhSoTheoThoiGian();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, "BCDSBH", frm.Text, frm.ValueList);
            }
        }

        private void iBaoCaoPhanTichDoanhSo_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoDoanhSoTheoLoaiHang frm = new Windows.Report.frmBaoCaoDoanhSoTheoLoaiHang();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void iBaoCaoDoanhThuLoiNhuan_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoDoanhThuLoiNhuan frm = new Windows.Report.frmBaoCaoDoanhThuLoiNhuan();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, "BCKQKD", "Báo cáo doanh thu và lợi nhuận", frm.ValueList);
            }
        }

        private void iBaoCaoCNPS_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoCongNoPS frm = new Windows.Report.frmBaoCaoCongNoPS();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void iBaoCaoDoanhSoTheoKH_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoDoanhSoTheoKhachHang frm = new Windows.Report.frmBaoCaoDoanhSoTheoKhachHang();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            CheckSo();
        }

        private void CheckSo()
        {
            string sErr = "";
            BUS.REFERGDControl ctr = new BUS.REFERGDControl();
            DataTable dt = ctr.GetAll(ref sErr);
            if (sErr == "")
            {
                if (dt.Rows.Count > 0)
                {
                    DTO.REFERGDInfo inf = new DTO.REFERGDInfo(dt.Rows[0]);

                    if (status != inf.KHOASO)
                    {
                        XtraMessageBox.Show("Tình trạng sổ đã bị thay đổi", "Thông báo");
                        frmMain_Load(null, null);
                        ClearMdi();
                    }

                }
            }
        }
        private void ClearMdi()
        {
            foreach (Control x in this.Controls)
            {
                if (x is MdiClient)
                {
                    for (int i = x.Controls.Count - 1; i >= 0; i--)
                    {
                        Control y = x.Controls[i];
                        if (!(y is PrintPreview))
                            x.Controls.Remove(y);
                    }
                }
            }
        }

        private void iBaoCaoThuChiTMTheoNgay_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoNKGiaoDichTheoNgay frm = new Windows.Report.frmBaoCaoNKGiaoDichTheoNgay();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }

        private void iBaoCaoChiTietNK_ItemClick(object sender, ItemClickEventArgs e)
        {
            Windows.Report.frmBaoCaoCTNK frm = new Windows.Report.frmBaoCaoCTNK();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                ShowReport(frm.DataSource, frm.Type, frm.Text, frm.ValueList);
            }
        }


    }
}
